#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : test10_user_and_terminal_p1.py
@Time : 2025/2/27 14:19
@Author: Wangwc
@Describe:  用户管理和终端机P1级用例
"""
import random
import warnings
import os

import openpyxl
from urllib3.exceptions import InsecureRequestWarning

warnings.filterwarnings("ignore", category=InsecureRequestWarning)

import time
import allure
import pytest

from faker import Faker

from business.UserApi import UserApi
from business.SystemApi import SystemApi
from utils.login import Login
from commons.logger import log
from utils.config_tools import Config
from commons.fake_data import Fake, fake_name_list
from config.path import EXCEL_DIR

fake = Faker()

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = "user.ini"
login = Login(config_name=config_name)
config = Config(config_name=config_name)

# TODO 用户名暂时所有测试用例统一，因为后面的测试用例需要使用
username = Fake.generate_english_username()
raw_passwd = Fake.generate_password()

# TODO 通过链接邀请创建用户的账号、密码
new_username = Fake.generate_english_username()
new_raw_passwd = Fake.generate_password()

# TODO 新增用户组名称
group_name = Fake.generate_english_username()

# 全局变量存储 token
global_token = None


def get_token():
    global global_token
    if global_token is None:
        global_token = login.login()
    return global_token


@pytest.fixture(scope="function")
def user_api():
    """
    用于初始化UserApi客户端的夹具
    """
    token = get_token()
    api = UserApi(token, configname=config_name)
    return api


@pytest.fixture(scope="function")
def system_api():
    """
    用于初始化SystemApi客户端的夹具
    """
    token = get_token()
    api = SystemApi(token, configname=config_name)
    return api


def convert_permission(permission):
    """
    转换 permission 的值
    :param permission: 原始的 permission 值
    :return: 转换后的 permission 值
    """
    if permission == -1:
        return 0
    elif permission == 1:
        return 7
    return 5


def handle_api_call(api_method, *args, attach_to_allure=True, format_result=None, **kwargs):
    if not callable(api_method):
        raise TypeError("api_method 参数必须是可调用对象（如函数或方法）")
    if attach_to_allure is not None and not isinstance(attach_to_allure, bool):
        raise TypeError("attach_to_allure 参数必须是布尔类型或者为 None")
    if format_result is not None and not callable(format_result):
        raise TypeError("format_result 参数必须是可调用对象（如函数）或者为 None")

    max_retries = 3
    for retry in range(max_retries):
        try:
            result = api_method(*args, **kwargs)
            if attach_to_allure:
                if format_result:
                    formatted_result = format_result(result)
                else:
                    formatted_result = str(result)
                allure.attach(formatted_result, f"{api_method.__name__} 调用结果", allure.attachment_type.TEXT)
            log.info(f"{api_method.__name__} 调用成功")
            return result
        except Exception as e:
            allure.attach(str(e), f"{api_method.__name__} 调用错误信息", allure.attachment_type.TEXT)
            log.error(f"{api_method.__name__} 调用出现错误: {e}", exc_info=True)
            # 假设根据错误信息判断 token 过期
            if "token 过期" in str(e) and retry < max_retries - 1:
                global global_token
                global_token = login.login()
                api_method.__self__.token = global_token
                continue
            elif isinstance(e, ConnectionError):
                log.error("连接错误，可能是网络问题，请检查网络连接。")
            elif isinstance(e, ValueError):
                log.error("值错误，可能是传入的参数有误，请检查参数。")
            raise


@allure.feature("控制面板-用户管理&终端-P1级用例")
class TestUserManagement():
    @allure.title("刷新用户权限")
    def test_refresh_user_permission(self, user_api):
        with allure.step("获取用户列表信息"):
            user_list = handle_api_call(user_api.get_user_list)
            index = random.randint(0, len(user_list) - 1)
            role = user_list[index].get('role')
            groups = user_list[index].get('groups')
            gids = [group.get('gid') for group in groups if group.get('name') != 'admin' and group.get('name') != 'users']


        with allure.step("刷新用户权限"):
            handle_api_call(user_api.get_user_group_permission, role, gids)
            time.sleep(0.5)

    @allure.title("创建用户名支持各种字符串")
    def test_username_with_any_str(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token,raw_passwd)

        with allure.step("创建用户"):
            handle_api_call(user_api.create_user, new_name, passwd)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            results = handle_api_call(user_api.get_user_list)
            user_name_list = [user.get('username') for user in results]
            assert new_name in user_name_list,f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token,password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-验证邮箱")
    def test_create_user_with_email(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            email = fake.email()

        with allure.step("创建用户指定邮箱"):
            handle_api_call(user_api.create_user, new_name, passwd,email=email)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            results = handle_api_call(user_api.get_user_list)
            user_name_list = [user.get('username') for user in results]
            assert new_name in user_name_list, f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-验证描述信息")
    def test_create_user_with_description(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            paragraph = fake.paragraph()

        with allure.step("创建用户添加描述"):
            handle_api_call(user_api.create_user, new_name, passwd, description=paragraph)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            results = handle_api_call(user_api.get_user_list)
            user_name_list = [user.get('username') for user in results]
            assert new_name in user_name_list, f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建普通用户")
    def test_create_user(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建普通用户"):
            handle_api_call(user_api.create_user, new_name, passwd, role='users')
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'users', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建管理员用户")
    def test_create_admin(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-加入单个用户组")
    def test_create_user_with_one_group(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("获取用户组信息"):
            group_list = handle_api_call(user_api.get_user_group_list)
            group_name = group_list[random.randint(0,len(group_list)-1)].get('groupname')

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd,groups=[{'name': group_name}])
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-加入多个用户组")
    def test_create_user_with_all_group(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("获取用户组信息"):
            group_list = handle_api_call(user_api.get_user_group_list)
            groups = [{'name':group.get('groupname')} for group in group_list]

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd, groups=groups)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-启用个人文件夹限额")
    def test_create_user_personal_folder_limit_quota(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建管理员用户"):
            set_quota = random.randint(1,20)
            handle_api_call(user_api.create_user, new_name, passwd,dir_quota=set_quota)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"
            assert user_info.get('enable_home_dir') == True, f"用户名{new_name}创建失败，预期开启个人文件夹，实际结果为：{user_info.get('enable_home_dir')}"
            assert user_info.get('dir_quota') == set_quota, f"用户名{new_name}创建失败"


        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-启用个人文件夹不限额")
    def test_create_user_personal_folder_without_limit_quota(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"
            assert user_info.get(
                'enable_home_dir') == True, f"用户名{new_name}创建失败，预期开启个人文件夹，实际结果为：{user_info.get('enable_home_dir')}"
            assert user_info.get('dir_quota') == 0, f"用户名{new_name}创建失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-不启用个人文件夹")
    def test_create_user_without_personal_folder(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd,enable_home_dir=False)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"
            assert user_info.get(
                'enable_home_dir') == False, f"用户名{new_name}创建失败，预期不开启个人文件夹，实际结果为：{user_info.get('enable_home_dir')}"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("创建用户-不允许更改密码")
    def test_create_user_deny_change_pwd(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建管理员用户"):
            handle_api_call(user_api.create_user, new_name, passwd, deny_change_pwd=True)
            time.sleep(0.5)

        with allure.step("确认用户成功创建"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            user_info = handle_api_call(user_api.get_user_information, uid)
            assert user_info.get('role') == 'admin', f"用户名{new_name}创建失败"
            assert user_info.get('username'), f"用户名{new_name}创建失败"
            assert user_info.get('deny_change_pwd') == True, f"用户名{new_name}创建失败，预期无法修改密码，实际结果为：{user_info.get('deny_change_pwd')}"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("用户管理-立即停用用户")
    def test_deactivate_user_immediately(self, user_api):
        with allure.step("构建用户名"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("创建用户"):
            handle_api_call(user_api.create_user, new_name, passwd, role='users')
            time.sleep(0.5)

        with allure.step("使用新用户登录"):
            new_rsa_token = login.verify_check(username=new_name)
            new_passwd = login.data_encrypt.rsa_passwd(new_rsa_token, raw_passwd)
            token = login.login(username=new_name, password=new_passwd)
            assert token is not None,f"用户名{new_name}登录失败"

        with allure.step("停用用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)
            handle_api_call(user_api.edit_user, new_name,uid,role='users',expire_time=1)
            time.sleep(0.5)

        with allure.step("确认用户成功停用"):
            user_info = handle_api_call(user_api.get_user_information, uid)
            log.info(f"停用用户后获取的用户信息为：{user_info}")
            new_rsa_token = login.verify_check(username=new_name)
            new_passwd = login.data_encrypt.rsa_passwd(new_rsa_token, raw_passwd)
            log.info(f"确认用户是否成功停用这里获取到的rsa_token，密码为：{new_rsa_token}、{new_passwd}")
            response = login.login(username=new_name, password=new_passwd)
            log.info(f"获取到的res结果为：{response}")
            assert response.get('msg') == "The account has been disabled" or response.get('msg') == '账号已经被停用', f"用户名{new_name}停用失败"

        with allure.step("删除用户"):
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

    @allure.title("用户组管理-用户组描述信息验证")
    def test_add_user_group_description(self, user_api):
        with allure.step("获取当前用户组列表"):
            user_group_list = handle_api_call(user_api.get_user_group_list)

        with allure.step("新增用户组-描述信息"):
            paragraph = fake.paragraph()
            gid = handle_api_call(user_api.create_user_group, group_name,description=paragraph)
            time.sleep(1)

        with allure.step("再次获取当前用户组列表"):
            new_user_group_list = handle_api_call(user_api.get_user_group_list)
            results = handle_api_call(user_api.get_group_info_by_id,gid)
            assert len(new_user_group_list) == len(user_group_list) + 1, "新增用户组后，用户组列表长度应该增加1"
            assert results.get('description') == paragraph, f"新增用户组后，用户组描述信息应该为{paragraph}，实际结果为：{results.get('description')}"

        with allure.step("删除用户组"):
            handle_api_call(user_api.delete_user_group, gid)

    @allure.title("用户组管理-给用户组添加成员")
    def test_group_add_users(self, user_api):
        with allure.step("随机获取1个用户组的信息"):
            user_group_list = handle_api_call(user_api.get_user_group_list)
            group_info = user_group_list[random.randint(0, len(user_group_list) - 1)]
            gid = group_info.get('gid')
            group_name = group_info.get('group_name')
            user_number = len(group_info.get('users')) if group_info.get('users') is not None else 0

        with allure.step("给用户组添加成员"):
            user_list = handle_api_call(user_api.get_user_list)
            add_user_list = [{'name': user_list[random.randint(1,len(user_list)-1)].get('username')}]
            handle_api_call(user_api.edit_user_group, group_name,gid, users=add_user_list)
            time.sleep(1)

        with allure.step("再次获取当前用户组信息"):
            new_group_info = handle_api_call(user_api.get_group_info_by_id,gid)
            assert len(new_group_info.get('users')) == len(add_user_list), f"给用户组添加成员后，用户组成员数量应该为{len(add_user_list)}，实际结果为：{len(new_group_info.get('users'))}"

    @allure.title("用户组管理-给用户组删除成员")
    def test_group_delete_users(self, user_api):
        with allure.step("随机获取1个用户组的信息"):
            user_group_list = handle_api_call(user_api.get_user_group_list)
            gid_list = [group.get('gid') for group in user_group_list if group.get('users') is not None]
            gid = random.choice(gid_list) if gid_list else None

        with allure.step("给用户组删除成员"):
            group_info = handle_api_call(user_api.get_group_info_by_id,gid)
            users = group_info.get('users')
            set_users = [{'name': user.get('name')} for user in users[1:] if user.get('name') is not None]
            handle_api_call(user_api.edit_user_group, group_name, gid, users=set_users)
            time.sleep(1)

        with allure.step("再次获取当前用户组信息"):
            new_group_info = handle_api_call(user_api.get_group_info_by_id, gid)
            new_users = new_group_info.get('users')
            assert len(new_users) == len(set_users), f"给用户组删除成员后，用户组成员数量应该为{len(set_users)}，实际结果为：{len(new_users)}"

    @allure.title("用户组管理-更改用户组权限")
    def test_change_group_permission(self, user_api):
        with allure.step("获取用户组当前权限"):
            user_group_list = handle_api_call(user_api.get_user_group_list)
            gid = user_group_list[random.randint(0, len(user_group_list) - 1)].get('gid')
            permissions = handle_api_call(user_api.get_group_permission_by_id,gid)

        with allure.step("更改用户组权限"):
            try:
                permission_list = [
                    {
                        'path': permission.get('path'),
                        'permission': convert_permission(permission.get('permission'))
                    }
                    for permission in permissions
                ]
                handle_api_call(user_api.set_group_permission, gid, list=permission_list)
                time.sleep(1)
            except Exception as e:
                log.error(f"更改用户组权限时出现异常，异常信息: {str(e)}")
        # 这里可以根据实际情况进行更详细的异常处理

        with allure.step("确认用户组权限更改成功"):
            try:
                new_permissions = handle_api_call(user_api.get_group_permission_by_id, gid)
                new_permission_list = [
                    {
                        'path': permission.get('path'),
                        'permission': permission.get('permission')
                    }
                    for permission in new_permissions
                ]
            except Exception as e:
                log.error(f"确认用户组权限更改时出现异常，异常信息: {str(e)}")
            assert permission_list == new_permission_list, f"用户组权限更改后，权限列表应该为{new_permission_list}，实际结果为：{permission_list}"

    @allure.title("用户管理-高级设置更改最短密码长度")
    def test_min_passwd_length(self, user_api):
        with allure.step("修改最短密码长度"):
            min_length = random.randint(10, 15)
            handle_api_call(user_api.set_global_config, min_length=min_length)
            time.sleep(1)

        with allure.step("确认成功修改最短密码长度"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get('min_length') == min_length, f"最短密码长度应该为{min_length}，实际结果为：{results.get('min_length')}"

        with allure.step("合格密码长度的用户可以成功创建"):
            name_list = fake_name_list()
            name = random.choice(name_list)
            raw_passwd = Fake.generate_password(min=15, max=20)
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            res = handle_api_call(user_api.create_user, name, passwd)
            assert res.json().get('code') == 200, f"预期创建用户成功，实际结果为：{res.json()}"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, name)
            rsa_token = login.verify_check()
            password = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, password)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)
            time.sleep(0.5)

        with allure.step("不合格密码长度的用户会创建失败"):
            new_name = random.choice(name_list)
            raw_passwd = Fake.generate_password(min=6, max=8)
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1028, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'Insufficient password length' in new_res.json().get('debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

    @allure.title("用户管理-高级设置阻止包含用户名称")
    def test_passwd_contain_username(self, user_api):
        with allure.step("设置阻止包含用户名称"):
            handle_api_call(user_api.set_global_config, disable_contain_key=True)
            time.sleep(1)

        with allure.step("确认成功设置阻止包含用户名称"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get(
                'disable_contain_key') == True, f"阻止包含用户名称应该为True，实际结果为：{results.get('disable_contain_key')}"

        with allure.step("验证密码包含用户名的用户会创建失败"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            fake_passwd = Fake.generate_password()
            raw_passwd = f"{new_name}{fake_passwd}"
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1029, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'Password cannot use username' in new_res.json().get('debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

    @allure.title("用户管理-高级设置阻止常用密码")
    def test_disable_common_passwd(self, user_api):
        with allure.step("设置阻止包含常用密码"):
            handle_api_call(user_api.set_global_config, disable_common_pwd=True)
            time.sleep(1)

        with allure.step("确认成功设置阻止包含常用密码"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get(
                'disable_common_pwd') == True, f"阻止常用密码应该为True，实际结果为：{results.get('disable_common_pwd')}"

        with allure.step("验证设置常用密码的用户会创建失败"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            passwords = [
                "password", "guest", "qwerty", "012345", "0123456", "01234567", "012345678", "0123456789", "123456",
                "1234567", "12345678", "123456789", "1234567890",
                "col123456", "111111", "123123", "000000", "555555", "666666", "123321", "654321", "7777777"
            ]
            raw_passwd = random.choice(passwords)
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1030, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'It cannot be a simple common password' in new_res.json().get('debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

    @allure.title("用户管理-高级设置必须同时包含字母大小写")
    def test_must_contain_case(self, user_api):
        with allure.step("设置必须同时包含字母大小写"):
            handle_api_call(user_api.set_global_config, must_contain_case=True)
            time.sleep(1)

        with allure.step("确认成功设置必须同时包含字母大小写"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get(
                'must_contain_case') == True, f"必须同时包含字母大小写应该为True，实际结果为：{results.get('must_contain_case')}"

        with allure.step("验证设置不同时包含字母大小写密码的用户会创建失败"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            fake_passwd = Fake.generate_password()
            raw_passwd = fake_passwd.upper()
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1031, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'Contain both uppercase and lowercase letters' in new_res.json().get(
                'debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

    @allure.title("用户管理-高级设置必须至少包含1位数字")
    def test_must_contain_num(self, user_api):
        with allure.step("设置必须至少包含1位数字"):
            handle_api_call(user_api.set_global_config, must_contain_num=True)
            time.sleep(1)

        with allure.step("确认成功设置必须至少包含1位数字"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get(
                'must_contain_num') == True, f"必须包含1位数字应该为True，实际结果为：{results.get('must_contain_num')}"

        with allure.step("验证设置不包含1位数字密码的用户会创建失败"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            fake_passwd = Fake.generate_password()
            raw_passwd = ''.join([c for c in fake_passwd if not c.isdigit()])
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1032, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'It must contain at least one number' in new_res.json().get(
                'debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

    @allure.title("用户管理-高级设置必须至少包含1位特殊字符")
    def test_must_contain_special_char(self, user_api):
        with allure.step("设置必须至少包含1位特殊字符"):
            handle_api_call(user_api.set_global_config, must_contain_special_char=True)
            time.sleep(1)

        with allure.step("确认成功设置必须至少包含1位特殊字符"):
            results = handle_api_call(user_api.get_global_config)
            assert results.get(
                'must_contain_special_char') == True, f"阻止包含用户名称应该为True，实际结果为：{results.get('must_contain_special_char')}"

        with allure.step("验证设置不包含1位特殊字符密码的用户会创建失败"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            fake_passwd = Fake.generate_password()
            raw_passwd = ''.join(c for c in fake_passwd if c.isalnum())
            log.debug(f"设置的未加密的密码为：{raw_passwd}")
            ras_token = login.verify_check()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)
            new_res = handle_api_call(user_api.create_user, new_name, new_passwd)
            assert new_res.json().get('code') == 1033, f"预期创建用户失败，实际结果为：{new_res.json()}"
            assert 'It must contain at least one special character' in new_res.json().get(
                'debug'), f"预期创建用户失败，实际结果为：{new_res.json()}"

        with allure.step("恢复默认设置"):
            handle_api_call(user_api.set_global_config)
            time.sleep(1)

    @allure.title("用户管理-验证H5邀请链接的用户名格式")
    def test_confirm_invite_username(self, user_api):
        with allure.step("获取邀请码"):
            my_username = config.read_config_ini('user', 'user_name')
            uid = handle_api_call(user_api.get_user_uid_by_username, my_username)
            invite_code = handle_api_call(user_api.get_invite_state, uid)

        with allure.step("获取uglink信息"):
            result = handle_api_call(user_api.get_uglink_status)
            internalDomain = result.get('internalDomain')

        with allure.step("校验用户名信息"):
            new_user_name = Fake.generate_english_username()
            data = handle_api_call(user_api.check_username, internalDomain, invite_code, new_user_name)
            assert data == {}, f'用户名{new_user_name}已存在'

        with allure.step("获取当前用户rsatoken"):
            ras_token = handle_api_call(user_api.get_invite_rsatoken, internalDomain, my_username)
            raw_passwd = Fake.generate_password()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("申请创建用户"):
            invite_list = handle_api_call(user_api.get_user_invite_list)
            handle_api_call(user_api.user_invite, internalDomain, invite_code, new_user_name, new_passwd, email='',
                            reason='')
            time.sleep(1)
            new_invite_list = handle_api_call(user_api.get_user_invite_list)
            assert len(new_invite_list) == len(invite_list) + 1, "邀请用户后，邀请列表长度应该增加1"

        with allure.step("删除申请纪录"):
            invite_id = handle_api_call(user_api.get_invite_id_by_username, new_user_name)
            handle_api_call(user_api.delete_invite, invite_id)

    @allure.title("用户管理-验证H5邀请链接的密码格式")
    def test_confirm_invite_password(self, user_api):
        with allure.step("获取邀请码"):
            my_username = config.read_config_ini('user', 'user_name')
            uid = handle_api_call(user_api.get_user_uid_by_username, my_username)
            invite_code = handle_api_call(user_api.get_invite_state, uid)

        with allure.step("获取uglink信息"):
            result = handle_api_call(user_api.get_uglink_status)
            internalDomain = result.get('internalDomain')

        with allure.step("校验用户名信息"):
            new_user_name = Fake.generate_english_username()
            data = handle_api_call(user_api.check_username, internalDomain, invite_code, new_user_name)
            assert data == {}, f'用户名{new_user_name}已存在'

        with allure.step("获取当前用户rsatoken"):
            ras_token = handle_api_call(user_api.get_invite_rsatoken, internalDomain, my_username)
            raw_passwd = Fake.generate_password()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("申请创建用户"):
            invite_list = handle_api_call(user_api.get_user_invite_list)
            handle_api_call(user_api.user_invite, internalDomain, invite_code, new_user_name, new_passwd, email='',
                            reason='')
            time.sleep(1)
            new_invite_list = handle_api_call(user_api.get_user_invite_list)
            assert len(new_invite_list) == len(invite_list) + 1, "邀请用户后，邀请列表长度应该增加1"

        with allure.step("删除申请纪录"):
            invite_id = handle_api_call(user_api.get_invite_id_by_username, new_user_name)
            handle_api_call(user_api.delete_invite, invite_id)

    @allure.title("用户管理-验证H5邀请链接添加电子邮件")
    def test_confirm_invite_email(self, user_api):
        with allure.step("获取邀请码"):
            my_username = config.read_config_ini('user', 'user_name')
            uid = handle_api_call(user_api.get_user_uid_by_username, my_username)
            invite_code = handle_api_call(user_api.get_invite_state, uid)

        with allure.step("获取uglink信息"):
            result = handle_api_call(user_api.get_uglink_status)
            internalDomain = result.get('internalDomain')

        with allure.step("校验用户名信息"):
            new_user_name = Fake.generate_english_username()
            data = handle_api_call(user_api.check_username, internalDomain, invite_code, new_user_name)
            assert data == {}, f'用户名{new_user_name}已存在'

        with allure.step("获取当前用户rsatoken"):
            ras_token = handle_api_call(user_api.get_invite_rsatoken, internalDomain, my_username)
            raw_passwd = Fake.generate_password()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("申请创建用户"):
            invite_list = handle_api_call(user_api.get_user_invite_list)
            email = Fake.fake_email()
            handle_api_call(user_api.user_invite, internalDomain, invite_code, new_user_name, new_passwd, email=email,
                            reason='')
            time.sleep(1)
            new_invite_list = handle_api_call(user_api.get_user_invite_list)
            assert len(new_invite_list) == len(invite_list) + 1, "邀请用户后，邀请列表长度应该增加1"

        with allure.step("删除申请纪录"):
            invite_id = handle_api_call(user_api.get_invite_id_by_username, new_user_name)
            handle_api_call(user_api.delete_invite, invite_id)

    @allure.title("用户管理-验证H5邀请链接添加申请理由")
    def test_confirm_invite_reason(self, user_api):
        with allure.step("获取邀请码"):
            my_username = config.read_config_ini('user', 'user_name')
            uid = handle_api_call(user_api.get_user_uid_by_username, my_username)
            invite_code = handle_api_call(user_api.get_invite_state, uid)

        with allure.step("获取uglink信息"):
            result = handle_api_call(user_api.get_uglink_status)
            internalDomain = result.get('internalDomain')

        with allure.step("校验用户名信息"):
            new_user_name = Fake.generate_english_username()
            data = handle_api_call(user_api.check_username, internalDomain, invite_code, new_user_name)
            assert data == {}, f'用户名{new_user_name}已存在'

        with allure.step("获取当前用户rsatoken"):
            ras_token = handle_api_call(user_api.get_invite_rsatoken, internalDomain, my_username)
            raw_passwd = Fake.generate_password()
            new_passwd = login.data_encrypt.rsa_passwd(ras_token, raw_passwd)

        with allure.step("申请创建用户"):
            invite_list = handle_api_call(user_api.get_user_invite_list)
            reason = fake.paragraph()
            handle_api_call(user_api.user_invite, internalDomain, invite_code, new_user_name, new_passwd, email="",
                            reason=reason)
            time.sleep(1)
            new_invite_list = handle_api_call(user_api.get_user_invite_list)
            assert len(new_invite_list) == len(invite_list) + 1, "邀请用户后，邀请列表长度应该增加1"

        with allure.step("删除申请纪录"):
            invite_id = handle_api_call(user_api.get_invite_id_by_username, new_user_name)
            handle_api_call(user_api.delete_invite, invite_id)

    @allure.title("用户管理-验证导入用户时用户名为UGOS")
    def test_confirm_import_name_with_ugos(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data,file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("更改用户名为UGOS"):
            user_list[0]['username'] = 'UGOS'
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert 'UGOS' in [user['username'] for user in user_list], "用户名UGOS应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, 'UGOS')
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user','user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid,x_curpass_token)

    @allure.title("用户管理-验证导入用户时角色为管理员")
    def test_confirm_import_admin_user(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("更改用户角色为管理员"):
            user_list[0]['role'] = 'admin'
            username = Fake.generate_english_username()
            user_list[0]['username'] = username
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)

    @allure.title("用户管理-验证导入用户时角色为普通用户")
    def test_confirm_import_users(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("更改用户角色为管理员"):
            user_list[0]['role'] = 'users'
            username = Fake.generate_english_username()
            user_list[0]['username'] = username
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)

    @allure.title("用户管理-验证导入用户时添加用户描述")
    def test_confirm_import_user_with_description(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("给导入用户添加描述信息"):
            paragraph = fake.paragraph()
            username = Fake.generate_english_username()
            user_list[0]['username'] = username
            user_list[0]['description'] = paragraph
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)

    @allure.title("用户管理-验证导入用户时添加邮件")
    def test_confirm_import_user_with_email(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("给导入用户添加邮件信息"):
            email = fake.email()
            username = Fake.generate_english_username()
            user_list[0]['username'] = username
            user_list[0]['email'] = email
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)

    @allure.title("用户管理-验证导入用户时添加用户组")
    def test_confirm_import_user_with_group(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("给导入用户添加邮件信息"):
            group_list = handle_api_call(user_api.get_user_group_list)
            groups = [{'gid':group.get('gid'),'name': group.get('groupname')} for group in group_list]
            username = Fake.generate_english_username()
            user_list[0]['username'] = username
            user_list[0]['groups'] = groups
            handle_api_call(user_api.import_user_commit, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)

    @allure.title("用户管理-验证导入用户时要求首次登录修改密码")
    def test_confirm_import_user_with_change_passwd(self, user_api):
        with allure.step("导入用户信息表"):
            file_path = os.path.join(EXCEL_DIR, "DX4600-D5C2-用户导入模板.xlsx")
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                user_list = handle_api_call(user_api.import_excel_user_data, file_content)
            except FileNotFoundError:
                # 若文件未找到，记录错误信息
                allure.attach(f"文件 {file_path} 未找到", "错误信息", allure.attachment_type.TEXT)
                raise
            except Exception as e:
                # 捕获其他异常，记录错误信息
                allure.attach(f"读取文件或调用 API 时出现错误: {str(e)}", "错误信息", allure.attachment_type.TEXT)
                raise

        with allure.step("设置导入用户要求首次登录修改密码"):
            username = Fake.generate_english_username()
            passwd = Fake.generate_password()
            user_list[0]['username'] = username
            user_list[0]['password'] = passwd
            handle_api_call(user_api.import_user_commit,force_change_pwd=True, list=user_list)

        with allure.step("确认用户成功导入"):
            if handle_api_call(user_api.check_import_state):
                user_list = handle_api_call(user_api.get_user_list)
                assert username in [user['username'] for user in user_list], f"用户名{username}应该存在"

        with allure.step("确认用户首次登录修改密码"):
            rsa_token = login.verify_check(username=username)
            password = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            result = login.gernaral_login(username=username, password=password)
            assert result.get('enable_change_pwd') == True,f"用户首次登录应该要求修改密码"

        with allure.step("删除用户"):
            uid = handle_api_call(user_api.get_user_uid_by_username, username)
            rsa_token = login.verify_check()
            passwd = config.read_config_ini('user', 'user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(rsa_token, passwd)
            handle_api_call(user_api.delete_user, uid, x_curpass_token)


def get_excel_data(file_path="test_data.xlsx", sheet_name="Sheet1"):
    # 打开 Excel 文件
    workbook = openpyxl.load_workbook(file_path)
    # 获取指定工作表
    sheet = workbook[sheet_name]
    data = []
    # 从第二行开始遍历工作表的每一行
    for row in sheet.iter_rows(min_row=2, values_only=True):
        data.append(row)
    return data

excel_data_path = os.path.join(EXCEL_DIR, "用户管理ACL.xlsx")

@allure.feature("控制面板-用户管理&终端-P1级用例")
class TestUserManagementACL:
    @pytest.mark.parametrize(
        "data1,data2,data3,data4,data5,data6",
        get_excel_data(file_path=excel_data_path)
    )
    @allure.title("{data6}")  # 动态设置Allure报告标题
    def test_user_management_acl(self, user_api, data1, data2, data3, data4, data5, data6):
        with allure.step("创建用户"):
            name_list = fake_name_list()
            new_name = random.choice(name_list)
            fake_passwd = Fake.generate_password()
            ras_token = login.verify_check()
            passwd = login.data_encrypt.rsa_passwd(ras_token, fake_passwd)
            handle_api_call(user_api.create_user, new_name, passwd,role=data1)
            uid = handle_api_call(user_api.get_user_uid_by_username, new_name)

        with allure.step("给用户设置共享文件夹权限"):
            permissions = handle_api_call(user_api.get_user_permission,uid)
            set_permission = [{'path': item.get('path'), 'permission': data2} for item in permissions]
            handle_api_call(user_api.set_user_permission,uid,set_permission)

        with allure.step("创建用户组"):
            user_group_list = handle_api_call(user_api.get_user_group_list)
            group_names = [item.get('groupname') for item in user_group_list]
            while True:
                # 生成一个英文用户名作为用户组名
                group_name = Fake.generate_english_username()
                if group_name not in group_names:
                    break
            handle_api_call(user_api.create_user_group, group_name)
            gid = handle_api_call(user_api.get_gid_by_groupname, group_name)

        with allure.step("给用户组添加共享文件夹权限"):
            group_permissions = handle_api_call(user_api.get_group_permission_by_id, gid)
            set_group_permission = [{'path': item.get('path'), 'permission': data3} for item in group_permissions]
            handle_api_call(user_api.set_group_permission, gid, set_group_permission)

        with allure.step("将用户添加到用户组"):
            set_group = [{'name':group_name}] if data4 == '是' else []
            handle_api_call(user_api.edit_user, new_name, uid,role=data1,groups=set_group)

        with allure.step("确认用户实际权限"):
            new_permissions = handle_api_call(user_api.get_user_permission,uid)
            new_permission_list = [item.get('permission_mask') for item in new_permissions if item.get('name')!='迅雷下载']
            assert new_permission_list[random.randint(0,len(new_permission_list)-1)] == data5

        with allure.step("删除用户、用户组"):
            ras_token = login.verify_check()
            admin_passwd = config.read_config_ini('user','user_pwd')
            x_curpass_token = login.data_encrypt.rsa_passwd(ras_token, admin_passwd)
            handle_api_call(user_api.delete_user, uid,x_curpass_token)
            handle_api_call(user_api.delete_user_group, gid)


